package plugin.demo.shardingsphere.xa.config.v5_0_0.algorithms;

import lombok.Getter;
import lombok.Setter;
import org.apache.shardingsphere.sharding.spi.KeyGenerateAlgorithm;

import java.util.*;
import java.util.function.Function;

/**
 * @Author: Qiao Hang
 * @CreateDate: 2021/4/23 上午10:53
 * @UpdateDate:
 * @Description:
 */
public class ExtendsKeyGenericAlgorithm {

    /**
     * 扩展KeyGenericAlgorithm X_UUID 允许客户端注入UUID 的 processor，使定制化更为抽象.
     * @param <Processor>
     */
   public static class X_UUID<Processor extends Function<UUID,String>> implements KeyGenerateAlgorithm {

       @Getter
       @Setter
       private Properties props = new Properties();

       private Processor processor;

       @Override
       public Comparable<?> generateKey() {
           return processor.apply(UUID.randomUUID());
       }

       @Override
       public void init() {
           Object processor = props.get("processor");
           if(processor == null){
               this.processor = (Processor) new Function<UUID,String>(){
                   @Override
                   public String apply(UUID uuid) {
                       return uuid.toString();
                   }
               };
           }else if(processor instanceof Function){
               this.processor = (Processor) processor;
           }
           if(this.processor == null){
               throw new RuntimeException("X_UUID 's consumer function is not a standard Function<UUID,String>.");
           }
       }

       @Override
       public String getType() {
           return "X_UUID";
       }
   }

}
